package com.fs.service.Impl;

import com.fs.dto.OrderCreateDTO;
import com.fs.dto.OrderItemDTO;
import com.fs.entity.Order;
import com.fs.entity.OrderItem;
import com.fs.mapper.OrderItemMapper;
import com.fs.mapper.OrderMapper;
import com.fs.service.OrderService;
import com.fs.vo.OrderItemVO;
import com.fs.vo.OrderUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户端 - 订单业务实现类
 * 功能说明：
 *   1. 实现订单创建、支付、取消、确认收货、查询逻辑；
 *   2. 所有方法基于当前用户ID，防止越权操作；
 *   3. 支持后续扩展（退款、订单统计、超时自动取消等）。
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 创建订单
     */
    public String createOrder(OrderCreateDTO dto,Long userId) {
        String orderNo = "FL" + System.currentTimeMillis();

        // 计算订单总金额
        BigDecimal totalAmount = dto.getItems().stream()
                .map(i -> i.getPrice().multiply(BigDecimal.valueOf(i.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 构建订单对象
        Order order = Order.builder()
                .orderNo(orderNo)
                .userId(userId)
                .totalAmount(totalAmount)
                .payAmount(totalAmount)
                .discountAmount(BigDecimal.ZERO)
                .paymentMethod(dto.getPaymentMethod())
                .status(0) // 待支付
                .orderTime(LocalDateTime.now())
                .receiverName(dto.getReceiverName())
                .receiverPhone(dto.getReceiverPhone())
                .receiverAddress(dto.getReceiverAddress())
                .remark(dto.getRemark())
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .deleted(0)
                .build();

        orderMapper.insert(order);

        // 插入订单明细项
        for (OrderItemDTO itemDto : dto.getItems()) {
            OrderItem item = new OrderItem();
            BeanUtils.copyProperties(itemDto, item);
            item.setOrderId(order.getId());
            item.setSubtotal(itemDto.getPrice().multiply(BigDecimal.valueOf(itemDto.getQuantity())));
            item.setCreateTime(LocalDateTime.now());
            orderItemMapper.insert(item);
        }

        return "订单创建成功，订单号：" + orderNo;
    }

    /**
     * 查询用户订单列表
     */
    public List<OrderUserVO> listUserOrders(Integer status, Long userId) {
        List<Order> orders = orderMapper.selectByUserIdAndStatus(userId, status);

        // 封装VO
        return orders.stream().map(order -> {
            List<OrderItem> items = orderItemMapper.selectByOrderId(order.getId());
            List<OrderItemVO> itemVOs = items.stream()
                    .map(i -> new OrderItemVO(i.getProductId(), i.getProductName(),
                            i.getProductImage(), i.getPrice(), i.getQuantity(), i.getSubtotal()))
                    .collect(Collectors.toList());
            return OrderUserVO.builder()
                    .id(order.getId())
                    .orderNo(order.getOrderNo())
                    .status(order.getStatus())
                    .totalAmount(order.getTotalAmount())
                    .payAmount(order.getPayAmount())
                    .orderTime(order.getOrderTime())
                    .receiverName(order.getReceiverName())
                    .receiverPhone(order.getReceiverPhone())
                    .receiverAddress(order.getReceiverAddress())
                    .items(itemVOs)
                    .build();
        }).collect(Collectors.toList());
    }

    /**
     * 查询订单详情
     */
    @Override
    public OrderUserVO getOrderDetail(Long orderId, HttpServletRequest request) {
        Order order = orderMapper.selectById(orderId);
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        List<OrderItemVO> itemVOs = items.stream()
                .map(i -> new OrderItemVO(i.getProductId(), i.getProductName(),
                        i.getProductImage(), i.getPrice(), i.getQuantity(), i.getSubtotal()))
                .collect(Collectors.toList());

        return OrderUserVO.builder()
                .id(order.getId())
                .orderNo(order.getOrderNo())
                .status(order.getStatus())
                .totalAmount(order.getTotalAmount())
                .payAmount(order.getPayAmount())
                .orderTime(order.getOrderTime())
                .receiverName(order.getReceiverName())
                .receiverPhone(order.getReceiverPhone())
                .receiverAddress(order.getReceiverAddress())
                .items(itemVOs)
                .build();
    }

    /**
     * 模拟支付订单
     */
    @Override
    public String payOrder(Long orderId, HttpServletRequest request) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || order.getStatus() != 0) {
            return "支付失败：订单不存在或状态错误";
        }
        orderMapper.payOrder(orderId, 1); // 修改状态为待发货
        return "支付成功，等待发货。";
    }

    /**
     * 取消订单
     */
    @Override
    public String cancelOrder(Long orderId, HttpServletRequest request) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || order.getStatus() != 0) {
            return "取消失败：订单不存在或状态错误";
        }
        orderMapper.cancelOrder(orderId, 4);
        return "订单已取消。";
    }

    /**
     * 确认收货
     */
    @Override
    public String confirmOrder(Long orderId, HttpServletRequest request) {
        Order order = orderMapper.selectById(orderId);
        if (order == null || order.getStatus() != 2) {
            return "确认收货失败：订单不存在或状态错误";
        }
        orderMapper.confirmOrder(orderId, 3);
        return "收货成功，感谢您的购买。";
    }
}
